package blipappeal;

import java.util.*;
import com.google.wave.api.*;
import java.io.Serializable;

public class TopScores implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public final static String TOP_SCORE_KEY = "TOP_SCORE";
	// number of scores to store
	// store the ScoreEntry's sorted by
	private Map<String, Integer> blipScores = new TreeMap<String, Integer>();
	
	public TopScores() {
	}
	
	public void addBlip(Blip blip, int score) {
		blipScores.put(blip.getBlipId(), score);
	}
	
	public void removeBlip(Blip blip) {
		blipScores.remove(blip.getBlipId());
	}
	
	public List<String> getTopScores(int numScores) {
		List<String> topScores = new ArrayList<String>(numScores);
		Comparator<Map.Entry<String,Integer>> comparator = new Comparator<Map.Entry<String,Integer>>()
		{
		    public int compare(Map.Entry<String,Integer> entry1, Map.Entry<String,Integer> entry2)
		    {
		    	int scoreDif = entry1.getValue()  - entry2.getValue();
		        if (scoreDif == 0) {
		        	scoreDif = entry1.getKey().compareTo(entry2.getKey());
		        }
		        return scoreDif;
		    }
		};
		// create a list of the map entries so we can sort by score
		List<Map.Entry<String,Integer>> entries = new ArrayList<Map.Entry<String,Integer>>();
		entries.addAll(blipScores.entrySet());
		Collections.sort(entries, comparator);
		// copy the first numScores entries  of the sorted list into the return list
		int numCopied = 0;
		for (Map.Entry<String,Integer> e: entries) {
			topScores.add(e.getKey());
			
			if (numCopied++ >= numScores) {
				break;
			}
		}
		
		return topScores;
	}

}


